package com.zhen.controller;

import com.zhen.domain.User;
import com.zhen.validator.UserValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {

    private static final Log LOGGER = LogFactory.getLog(UserController.class);

    @Autowired
    @Qualifier("userValidator")
    private UserValidator userValidator;

    @RequestMapping(value="/{formName}")
    public String loginForm(@PathVariable String formName,Model model){
        User user = new User();
        model.addAttribute(user);
        return formName;
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@ModelAttribute User user,Model model,Errors errors){
        LOGGER.info(user);
        model.addAttribute("user",user);
        userValidator.validate(user,errors);
        if(errors.hasErrors()){
            return "loginForm";
        }
        return "success";
    }
}
